import React, { PropsWithChildren, useRef } from 'react';
import { Form, Input, Button, Checkbox, message, FormInstance } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { connect } from 'react-redux';
import * as actions from '../../../../store/actions/login'
import { login } from '../../../../api/login';
import { encryption, getResponseData, setSessionStore } from '../../../../utils/helpers';
import { LoginResponseData, LoginProps } from '../../../../api/types';
const tailLayout = {
    wrapperCol: { offset: 0, span: 16 },
};

// 获取导出的所有actions的类型即得到属性值
type LoginFormProps = typeof actions;
type Props = PropsWithChildren<LoginFormProps>
const LoginForm = (props: Props) => {
    // 校验成功
    const onFinish = async (values: LoginProps) => {
        // 加密 登录 获取解开返回类型
        const res = getResponseData<LoginResponseData>(await login(encryption(values) as LoginProps));
        if (res.code == 1) {
            message.success(res.msg + '，正在跳转到首页', 1000);
            // 重置表单值
            ref.current?.resetFields();

            // 存值到session中
            setSessionStore('token', res.data.token)
            setSessionStore('user', res.data)
            // 派发登录成功的action 存储登录状态等
            props.successLogin(res.data);
            // 登录成功，跳转到首页
            setTimeout(() => {
                props.go('/')
            }, 1100)
        } else {
            message.error(res.msg);
        }
    };
    // 校验失败
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
    };


    const ref = useRef<FormInstance>(null);
    return (
        <Form
            name="basic"
            ref={ref}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            key="loginForm"
        >
            <Form.Item
                name="username"
                rules={[{ required: true, message: '请输入用户名!' }]}
            >
                <Input placeholder="请输入用户名" prefix={<UserOutlined className="site-form-item-icon" />} />
            </Form.Item>

            <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
            >
                <Input.Password placeholder="请输入密码" prefix={<LockOutlined className="site-form-item-icon" />} />
            </Form.Item>
            <Form.Item {...tailLayout} name="remember" valuePropName="checked">
                <Checkbox>记住我</Checkbox>
            </Form.Item>

            <Form.Item {...tailLayout}>
                <Button type="primary" htmlType="submit" className='btn'>
                    登录
        </Button>
            </Form.Item>
            <span className='cs cm-color to-register' onClick={() => { props.changeTransform(false);/*跳转到注册页 */ }}>还没注册，点此去注册吧!</span>
        </Form>
    );
};

export default connect(() => ({}), actions)(LoginForm);